const text = function(msg) {
	uni.showToast({
		icon: 'none',
		title: msg,
		position: "top",
	});
}

const goPage = function(url, animation) {
	let animationType = animation ? animation : "slide-in-right"
	console.log("goPage:", url, animation)
	uni.navigateTo({
		url: url,
		animationType: animationType
	})
}
const goSwitch = function(url) {
	uni.switchTab({
		url: url
	})
}
const goReLaunch = function(url) {
	uni.reLaunch({
		url: url
	})
}
const goBack = () => {
	uni.navigateBack()
}
const goRedirectTo = (url) => {
	uni.redirectTo({
		url: url
	})
}



//js去掉两头空格	
const acg = function(str) {
	return str.replace(/^\s+|\s+$/g, "");
}
const find_array = function(arraytosearch, key, valuetosearch) {
	for (var i = 0; i < arraytosearch.length; i++) {
		if (arraytosearch[i][key] == valuetosearch) {
			return i;
		}
	}
	return null;
}

const http_builder_url = function(data) {
	if (typeof(data) == 'undefined' || data == null || typeof(data) != 'object') {
		return '';
	}
	var url = '';
	for (var k in data) {
		url += ((url.indexOf("=") != -1) ? "&" : "") + k + "=" + encodeURI(data[k]);
	}
	return url;
}

const clearNoNum = function(obj, num) { //计算小数保留值
	if (num == 0) return obj.value.replace(/^(0+)|[^\d]+/g, '');
	let reg = new RegExp("^\\D*(\\d*(?:\\.\\d{0," + num + "})?).*$", 'g');
	obj.value = obj.value.replace(reg, '$1');
	return obj.value.replace(reg, '$1');
}

//获取当前年月日时分
const getNowFormatDate = function() {
	var date = new Date(); //获取时间
	var year = date.getFullYear(); //年
	var month = date.getMonth() + 1 //月
	var strDate = date.getDate(); //日
	var hours = date.getHours(); //时
	var minutes = date.getMinutes(); //分
	var second = date.getSeconds(); //秒
	var currentdate = year +
		(month > 9 ? month : '0' + month) +
		(strDate > 9 ? strDate : '0' + strDate) +
		(hours > 9 ? hours : '0' + hours) +
		(minutes > 9 ? minutes : '0' + minutes)
	return currentdate;
}

//获取当前年月日时分
const getNowFormatDate_ymd = function() {
	var date = new Date(); //获取时间
	var year = date.getFullYear(); //年
	var month = date.getMonth() + 1 //月
	var strDate = date.getDate(); //日
	var hours = date.getHours(); //时
	var minutes = date.getMinutes(); //分
	var second = date.getSeconds(); //秒
	var currentdate = year + "-" + (month > 9 ? month : '0' + month) + "-" + (strDate > 9 ? strDate : '0' + strDate)
	return currentdate;
}

const numLength = function(obj) { //计算小数保留值
	let data = obj.split("")
	let ii = 0
	data.forEach((v, i) => {
		ii++
	})
	return ii;
}
//验证手机号是否合法
const checkPhone = function(mobile) {
	if (!(/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(mobile))) {
		return false;
	} else {
		return true;
	}
}
const sortFn = function(property) {
	return function(a, b) {
		var value1 = a[property];
		var value2 = b[property];
		return value1 - value2;
	}
}
//范围随机数
const randomNum = (min, max) => {
	let range = max - min;
	let rand = Math.random()
	let num = min + Math.round(rand * range)
	return num;
}

//排序 0 -> 1
const compare = function(prop) {
	return function(obj1, obj2) {
		var val1 = obj1[prop];
		var val2 = obj2[prop];
		if (val1 < val2) {
			return -1;
		} else if (val1 > val2) {
			return 1;
		} else {
			return 0;
		}
	}
}



const randomWord = function(randomFlag, min, max) {
	var str = "",
		range = min,
		arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
			'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E',
			'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
		];
	// 随机产生
	if (randomFlag) {
		range = Math.round(Math.random() * (max - min)) + min;
	}
	for (var i = 0; i < range; i++) {
		pos = Math.round(Math.random() * (arr.length - 1));
		str += arr[pos];
	}
	return str;
}

// 洗牌算法
const shuffle = (array) => {
	var m = array.length,
		t, i;
	while (m) {
		i = Math.floor(Math.random() * m--);
		t = array[m];
		array[m] = array[i];
		array[i] = t;
	}
	return array;
}



//数组排列组合
const getCombination = (array) => {
	let resultArr = [];
	array.forEach((arrItem) => {
		if (resultArr.length === 0) {
			let firstItem = [];
			arrItem.forEach(item => {
				firstItem.push([item]);
			})
			resultArr = firstItem
		} else {
			const emptyArray = [];
			resultArr.forEach((item) => {
				arrItem.forEach((value) => {
					emptyArray.push([...item, value])
				})
			})
			resultArr = emptyArray
		}
	});
	return resultArr;
};

const getBase64 = (imgUrl) => {
	window.URL = window.URL || window.webkitURL;
	var xhr = new XMLHttpRequest();
	xhr.open("get", imgUrl, true);
	// 至关重要
	xhr.responseType = "blob";
	xhr.onload = function() {
		if (this.status == 200) {
			//得到一个blob对象
			var blob = this.response;
			console.log("blob", blob)
			// 至关重要
			let oFileReader = new FileReader();
			oFileReader.onloadend = function(e) {
				// 此处拿到的已经是 base64的图片了
				let base64 = e.target.result;
				console.log(base64)
			};
			oFileReader.readAsDataURL(blob);
			//====为了在页面显示图片，可以删除====
			var img = document.createElement("img");
			img.onload = function(e) {
				window.URL.revokeObjectURL(img.src); // 清除释放
			};
			let src = window.URL.createObjectURL(blob);
			img.src = src
			//document.getElementById("container1").appendChild(img);
			//====为了在页面显示图片，可以删除====

		}
	}
	xhr.send();
}



const strLength = (str) => {
	var len = 0;
	for (var i = 0; i < str.length; i++) {
		var c = str.charCodeAt(i);
		//单字节加1
		if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
			len++;
		} else {
			//汉字加2
			len += 2;
		}
	}
	return Math.floor(len / 2);
}
const toMapAPP = (s_longitude, s_latitude, longitude, latitude, name) => {
	let url = "";
	let qqMapKey = "2BNBZ-XIE63-F523Z-YTWIM-674HJ-Y5FQ2"
	if (plus.os.name == "Android") { //判断是安卓端
		plus.nativeUI.actionSheet({ //选择菜单
				title: "选择地图应用",
				cancel: "取消",
				buttons: [{
						title: "腾讯地图"
					},
					{
						title: "百度地图"
					}, {
						title: "高德地图"
					}
				]
			},
			function(e) {
				switch (e.index) {
					//下面是拼接url,不同系统以及不同地图都有不同的拼接字段
					case 1:
						//注意referer=xxx的xxx替换成你在腾讯地图开发平台申请的key
						url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=${qqMapKey}`;
						break;
					case 2:
						url =
							`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`;
						break;
					case 3:
						url =
							`androidamap://route/plan?sourceApplication=maxuslife&sid=A&slat=${s_latitude }&slon=${s_longitude}&sname=我的位置&did=B&dlat=${latitude}&dlon=${longitude}&dname=${name}&dev=0&t=0`


						break;
					default:
						break;
				}
				if (url != "") {
					url = encodeURI(url);
					//plus.runtime.openURL(url,function(e){})调起手机APP应用
					plus.runtime.openURL(url, function(e) {
						plus.nativeUI.alert("本机未安装指定的地图应用");
					});
				}
			})
	} else {
		// iOS上获取本机是否安装了百度高德地图，需要在manifest里配置
		// 在manifest.json文件app-plus->distribute->apple->urlschemewhitelist节点下添加
		//（如urlschemewhitelist:["iosamap","baidumap"]）  
		plus.nativeUI.actionSheet({
			title: "选择地图应用",
			cancel: "取消",
			buttons: [{
				title: "腾讯地图"
			}, {
				title: "百度地图"
			}, {
				title: "高德地图"
			}]
		}, function(e) {
			switch (e.index) {
				case 1:
					url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=${qqMapKey}`;
					break;
				case 2:
					url =
						`baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
					break;
				case 3:
					url =
						`iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
					break;
				default:
					break;
			}
			if (url != "") {
				url = encodeURI(url);
				plus.runtime.openURL(url, function(e) {
					plus.nativeUI.alert("本机未安装指定的地图应用");
				});
			}
		})
	}
}

// 判断第三方程序(微信) 是否安装

// 平台		pname							action
// 微信 		com.tencent.mm 					weixin://
// QQ 		com.tencent.mobileqq 			mqq://
// 新浪微博 	com.sina.weibo 					sinaweibo://
// 淘宝 		com.taobao.taobao 				taobao://
// 支付宝 	com.eg.android.AlipayGphone 	alipay://
// 京东 		com.jingdong.app.mall 			openApp.jdMobile://
// 优酷 		com.youku.phone 				youku://
// 高度地图 	com.autonavi.minimap 			iosamap://
// 百度地图 	com.baidu.BaiduMap 				baidumap://
const checkApp = () => {
	let appList = []
	if (plus.runtime.isApplicationExist({
			pname: 'com.tencent.mm',
			action: 'weixin://'
		})) appList.push("微信");
	if (plus.runtime.isApplicationExist({
			pname: 'com.tencent.mobileqq ',
			action: 'mqq://'
		})) appList.push("QQ");
	if (plus.runtime.isApplicationExist({
			pname: 'com.sina.weibo',
			action: 'sinaweibo://'
		})) appList.push("新浪微博");
	if (plus.runtime.isApplicationExist({
			pname: 'com.taobao.taobao',
			action: 'taobao://'
		})) appList.push("淘宝");
	if (plus.runtime.isApplicationExist({
			pname: 'com.eg.android.AlipayGphone',
			action: 'alipay://'
		})) appList.push("支付宝");
	if (plus.runtime.isApplicationExist({
			pname: 'com.jingdong.app.mall',
			action: 'openApp.jdMobile://'
		})) appList.push("京东");
	if (plus.runtime.isApplicationExist({
			pname: 'com.autonavi.minimap',
			action: 'iosamap://'
		})) appList.push("高德地图");
	if (plus.runtime.isApplicationExist({
			pname: 'com.baidu.BaiduMap ',
			action: 'baidumap://'
		})) appList.push("百度地图");
	return appList
}




const base64ToFile = (dataurl, filename) => {

	//将base64转换为文件
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], filename, {
		type: mime
	});
}
// /*获取总内存*/

function getFileSize(bytes) {
	const units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
	let size = bytes;
	let unitIndex = 0;

	while (size >= 1024 && unitIndex < units.length - 1) {
		size /= 1024;
		unitIndex++;
	}

	// 保留两位小数，四舍五入
	size = Math.round(size * 100) / 100;

	return `${size} ${units[unitIndex]}`;
}

// /*获取总内存*/

function getMemInfo() {
	plus.android.importClass('java.io.BufferedReader')
	var localFileReader = plus.android.newObject('java.io.FileReader', '/proc/meminfo')
	var localBufferedReader = plus.android.newObject('java.io.BufferedReader', localFileReader, 8192)
	var str = localBufferedReader.readLine().toString();
	var totalMemStr = str;
	var avaMemStr = ''
	var i = 0
	while (i < 2) {
		str = localBufferedReader.readLine().toString();
		avaMemStr = str;
		i++
	}
	totalMemStr = (parseInt(totalMemStr.toUpperCase().replace(/(( )|(:)|[A-Z])/gi, '')) / 1024).toFixed(0)
	avaMemStr = (parseInt(avaMemStr.toUpperCase().replace(/(( )|(:)|[A-Z])/gi, '')) / 1024).toFixed(0)
	// console.log(totalMemStr);
	// console.log(avaMemStr);
	let total = parseInt(totalMemStr / 100)

	if (total < 32) {
		total = 32
	} else if (total > 32 && total <= 64) {
		total = 64
	} else if (total > 64 && total <= 128) {
		total = 128
	} else if (total > 128 && total <= 256) {
		total = 256
	} else if (total > 256 && total <= 512) {
		total = 512
	} else if (total > 512 && total <= 1024) {
		total = 1024
	}
	return {
		total: total,
		ava: parseInt(avaMemStr / 100)
	}
}

//冒泡法排序
const sortArr = (property) => {
	console.log(property)
	return function(a, b) {
		var value1 = a[property];
		var value2 = b[property];
		return value1 - value2;
	}
}




// 去重 ｛ name ｝
const unique = (arr1) => {
	const res = new Map()
	return arr1.filter((item) => !res.has(item.fileName) && res.set(item.fileName, 1))
}


const imageToJpg = (data) => {
	let obj = {}
	return obj
}

const sortDateArray = (arr) => {	
	var newArr = [];
	arr.forEach(function(oldData, i) {
		var index = -1;
		var createTime = oldData.date
		var alreadyExists = newArr.some(function(newData, j) {
			if (oldData.date.substring(0, 10) === newData.date.substring(
					0, 10)) {
				index = j;
				return true;
			}
		});
		if (!alreadyExists) {
			var res = [];
			res.push(oldData);
			newArr.push({
				date: oldData.date,
				res: res
			});
		} else {
			newArr[index].res.push(oldData);
		}
	});
	console.log(newArr)
	return newArr;


}






module.exports = {
	text,
	find_array,
	clearNoNum,
	getNowFormatDate,
	getNowFormatDate_ymd,
	numLength,
	compare,
	acg,
	checkPhone,
	sortFn,
	randomNum,
	randomWord,
	shuffle,
	getCombination,
	strLength,
	toMapAPP,
	getBase64,
	checkApp,
	base64ToFile,
	getMemInfo,
	sortArr,

	unique,
	getFileSize,

	imageToJpg,

	goPage,
	goSwitch,
	goReLaunch,
	goBack,
	goRedirectTo,
	sortDateArray






}